package com.carey.myblog.aspect;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("execution(* com.carey.myblog.controller..*(..))")
    public void requestServer() {
    }

    @Before("requestServer()")
    public void Before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        log.info("Request{}:",requestLog);
    }

    @After("requestServer()")
    public void After(){
        log.info("---------after----------");
    }

    @AfterReturning(returning="result",pointcut = "requestServer()")
    public void AfterReturning(Object result){
        log.info("result{}:"+result);
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class RequestLog{
    private String url;
    private String ip;
    private String classMethod;
    private Object[] args;

}
